package com.efounder.util;

import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnDismissListener;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.net.Uri;
import android.os.AsyncTask;
import android.util.Log;
import android.view.Gravity;
import android.widget.Toast;

import com.efounder.ospmobilelib.R;
import com.efounder.tbs.DisplayFileWithTbsUtil;
import com.efounder.utils.ResStringUtil;
import com.pansoft.resmanager.ResFileManager;
import com.utilcode.util.UriUtils;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.List;

/**
 * OA详情页面 点击附件 下载并打开附件
 * 
 * @author cherise
 * 
 */
@SuppressLint("DefaultLocale")
public class DownAttachUtil {

	private String directory;
	private Context mcontext;
	private String url;
	private String mcookie;
	private final String FRONTURL = "https://pgyd.zyof.com.cn/ESPWTN/servlet/DownLoad?cookie=&url=";
	private final String FFSFRONTURL = "https://pgyd.zyof.com.cn/ESPWTN/servlet/DownLoad2?cookie=&url=";
	private final String LEAVEURL = "https://pgyd.zyof.com.cn/ESPWTN/servlet/DownLoad3?cookie=&url=";

	public DownAttachUtil(Context mcontext, String url, String cookie) {
		super();
		this.mcontext = mcontext;
		this.url = FRONTURL + url;
		this.mcookie = cookie;
		directory = ResFileManager.MEETING;
		File file = new File(directory);
		if (!file.exists() && !file.isDirectory()) {
			System.out.println("//不存在");
			file.mkdir();
		} else {
			System.out.println("//目录存在");
		}

	}

	/**
	 * 此方法是给费用报销和请销假下载附件使用的
	 * 
	 * @param mcontext
	 * @param url
	 * @param cookie
	 * @param systemType
	 */
	public DownAttachUtil(Context mcontext, String url, String cookie,
						  String systemType) {
		super();
		this.mcontext = mcontext;
		if ("LEAVE".equals(systemType)) {
			this.url = LEAVEURL + url;
		} else if ("PGZB".equals(systemType)) {
			this.url = FFSFRONTURL + url;// 使用费用报销的下载招标的附件
		} else {
			this.url = FFSFRONTURL + url;

		}

		this.mcookie = cookie;
		directory = ResFileManager.MEETING;
		File file = new File(directory);
		if (!file.exists() && !file.isDirectory()) {
			System.out.println("//不存在");
			file.mkdir();
		} else {
			System.out.println("//目录存在");
		}

	}

	/**
	 * 执行下载
	 */
	public void taskStart() {
		DownloaderTask task = new DownloaderTask();
		task.execute(url);

	}

	// 内部类
	private class DownloaderTask extends AsyncTask<String, Void, String> {

		public DownloaderTask() {
		}

		@SuppressWarnings("deprecation")
		@Override
		protected String doInBackground(String... params) {
			String url = params[0];
			// Log.i("tag", "url="+url);
			// url = url.substring(0,url.lastIndexOf("&encoding=gbk"));
			String fileName = System.currentTimeMillis() + "";
			fileName += url.substring(url.lastIndexOf("."));
			// String fileName = url.substring(url.lastIndexOf(".") + 1);
			try {
				String tempFileName = URLEncoder.encode(
						url.substring(url.lastIndexOf("/") + 1), "GBK");
				url = url.replace(url.substring(url.lastIndexOf("/") + 1),
						tempFileName);
			} catch (UnsupportedEncodingException e1) {

				e1.printStackTrace();
			}

			fileName = URLDecoder.decode(fileName);
			Log.i("tag", "fileName=" + fileName);

			// File directory=Environment.getExternalStorageDirectory();
			File file = new File(directory, fileName);
			/*
			 * if(file.exists()){ Log.i("tag", "The file has already exists.");
			 * return fileName; }
			 */
			try {
				HttpClient client = new DefaultHttpClient();
				// client.getParams().setIntParameter("http.socket.timeout",3000);//设置超时
				HttpGet get = new HttpGet(url);

				// String cookie = CookieManager.getInstance().getCookie(url);
				get.addHeader("cookie", mcookie);
				HttpResponse response = client.execute(get);

				if (HttpStatus.SC_OK == response.getStatusLine()
						.getStatusCode()) {
					HttpEntity entity = response.getEntity();
					InputStream input = entity.getContent();

					writeToSDCard(fileName, input);

					input.close();
					// entity.consumeContent();
					return fileName;
				} else {
					return null;
				}
			} catch (Exception e) {
				e.printStackTrace();
				return null;
			}
		}

		@Override
		protected void onCancelled() {
			// TODO Auto-generated method stub
			super.onCancelled();
		}

		@Override
		protected void onPostExecute(String result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			closeProgressDialog();
			if (result == null) {
				Toast t = Toast.makeText(mcontext, ResStringUtil.getString(R.string.common_text_connect_error),
						Toast.LENGTH_LONG);
				t.setGravity(Gravity.CENTER, 0, 0);
				t.show();
				return;
			}

//			Toast t = Toast.makeText(mcontext, "已保存到SD卡", Toast.LENGTH_SHORT);
//			t.setGravity(Gravity.CENTER, 0, 0);
//			t.show();
			// File directory=Environment.getExternalStorageDirectory();
			File file = new File(directory, result);
			Log.i("tag", "Path=" + file.getAbsolutePath());

			try {
                //tbs加载
                if (DisplayFileWithTbsUtil.displayFile(mcontext, file.getAbsolutePath())) {
                    return;
                }
				Intent intent = getFileIntent(file);
				if (isIntentAvailable(mcontext, intent)) {
					mcontext.startActivity(intent);
				} else {
					Toast t1 = Toast.makeText(mcontext, "请安装该文件类型的程序！",
							Toast.LENGTH_LONG);
					t1.setGravity(Gravity.CENTER, 0, 0);
					t1.show();
				}
			} catch (Exception e) {
				Toast t2 = Toast.makeText(mcontext,
						"该文件打开失败，请检查手机是否存在打开该文件类型的程序。", Toast.LENGTH_LONG);
				t2.setGravity(Gravity.CENTER, 0, 0);
				t2.show();
			}

		}

		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			super.onPreExecute();
			showProgressDialog();
		}

		@Override
		protected void onProgressUpdate(Void... values) {
			// TODO Auto-generated method stub
			super.onProgressUpdate(values);
		}

	}

	private ProgressDialog mDialog;

	private void showProgressDialog() {
		if (mDialog == null) {
			mDialog = new ProgressDialog(mcontext);
			mDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);// 设置风格为圆形进度条
			mDialog.setMessage(ResStringUtil.getString(R.string.common_text_please_wait));
			mDialog.setIndeterminate(false);// 设置进度条是否为不明确
			mDialog.setCancelable(true);// 设置进度条是否可以按退回键取消
			mDialog.setCanceledOnTouchOutside(false);
			mDialog.setOnDismissListener(new OnDismissListener() {

				@Override
				public void onDismiss(DialogInterface dialog) {
					// TODO Auto-generated method stub
					mDialog = null;
				}
			});
			mDialog.show();

		}
	}
	private void closeProgressDialog() {
		try {
			if (mDialog != null) {
                mDialog.dismiss();
                mDialog = null;
            }
		} catch (Exception e) {
			mDialog = null;
			e.printStackTrace();
		}
	}

	public Intent getFileIntent(File file) {
		// Uri uri = Uri.parse("http://m.ql18.com.cn/hpf10/1.pdf");
		Uri uri = UriUtils.getUriForFile(file);
		String type = getMIMEType(file);
		Log.i("tag", "type=" + type);
		Intent intent = new Intent("android.intent.action.VIEW");
		intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
		intent.addCategory("android.intent.category.DEFAULT");
		intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		intent.setDataAndType(uri, type);
		return intent;
	}

	public void writeToSDCard(String fileName, InputStream input) {

		// if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
		// File directory=Environment.getExternalStorageDirectory();
		File file = new File(directory, fileName);
		// if(file.exists()){
		// Log.i("tag", "The file has already exists.");
		// return;
		// }
		try {
			FileOutputStream fos = new FileOutputStream(file);
			byte[] b = new byte[2048];
			int j = 0;
			while ((j = input.read(b)) != -1) {
				fos.write(b, 0, j);
			}
			fos.flush();
			fos.close();
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		/*
		 * }else{ Log.i("tag", "NO SDCard."); }
		 */
	}

	private String getMIMEType(File f) {
		String type = "";
		String fName = f.getName();
		/* 取得扩展名 */
		String end = fName
				.substring(fName.lastIndexOf(".") + 1, fName.length())
				.toLowerCase();

		/* 依扩展名的类型决定MimeType */
		if (end.equals("pdf")) {
			type = "application/pdf";//
		} else if (end.equals("m4a") || end.equals("mp3") || end.equals("mid")
				|| end.equals("xmf") || end.equals("ogg") || end.equals("wav")) {
			type = "audio/*";
		} else if (end.equals("3gp") || end.equals("mp4")) {
			type = "video/*";
		} else if (end.equals("jpg") || end.equals("gif") || end.equals("png")
				|| end.equals("jpeg") || end.equals("bmp")) {
			type = "image/*";
		} else if (end.equals("apk")) {
			/* android.permission.INSTALL_PACKAGES */
			type = "application/vnd.android.package-archive";
		} else if (end.equals("pptx") || end.equals("ppt")) {
			type = "application/vnd.ms-powerpoint";
		} else if (end.equals("docx") || end.equals("doc")) {
			type = "application/msword";
		} else if (end.equals("xlsx") || end.equals("xls")) {
			type = "application/vnd.ms-excel";
		} else {
			// /*如果无法直接打开，就跳出软件列表给用户选择 */
			type = "*/*";
		}
		return type;
	}

	/**
	 * 判断Intent 是否存在 防止崩溃
	 * 
	 * @param context
	 * @param intent
	 * @return
	 */
	private boolean isIntentAvailable(Context context, Intent intent) {
		final PackageManager packageManager = context.getPackageManager();
		List<ResolveInfo> list = packageManager.queryIntentActivities(intent,
				PackageManager.GET_ACTIVITIES);
		return list.size() > 0;
	}

}
